#encoding:utf-8
'''
Created on 2015年6月30日

@author: LWD
'''

import ConfigParser

try:
    import MySQLdb
except ImportError:
    raise ImportError("[E]: MySQLdb module not found!")

class CMySql:
    def __init__(self):
        self.Option = {"host" : "", "password" : "", "username" : "", "database" : "", "port" : 3306}
        
    def read_options_config(self):
        '''
        @todo: 通过读取配置文件设置数据库配置信息
        '''
        cf = ConfigParser.ConfigParser()
        cf.read("./../config/config.ini")
        
        self.Option["host"] = cf.get("mysql", "host")
        self.Option["password"] = cf.get("mysql", "password")
        self.Option["username"] = cf.get("mysql", "username")
        self.Option["database"] = cf.get("mysql", "database")
        # 端口有默认值，设置端口
        port = cf.get("mysql", "port")
        if not port.strip():
            self.Option["port"] = port
 
    def setoptions(self, host, pwd, user, db, port = 3306):
        '''
        @todo: 通过代码设置 数据库 配置信息
        '''
        self.Option["host"] = host
        self.Option["password"] = pwd
        self.Option["username"] = user
        self.Option["database"] = db
        self.Option["port"] = port
 
    def create_connection(self):
        '''
        @todo: 创建数据库连接
        '''
        # 判断 配置信息是否已经设置
        if not (self.Option["host"].strip() \
            and self.Option["password"] \
            and self.Option["username"] \
            and self.Option["database"]):
            print "please set options first"
            return
        
        try:
            #连接数据库
            self.db = MySQLdb.connect(
                        host = self.Option["host"],
                        user = self.Option["username"],
                        passwd = self.Option["password"],
                        db = self.Option["database"],
                        port = self.Option["port"],
                        charset="utf8")
        except Exception, e:
            print e
            raise Exception("[E] Cannot connect to %s" % self.Option["host"])
 
    def create_database(self, sqlstate):
        """
        @todo: sqlstate可以自己改成其他参数，下同
        """
        self.cursor = self.db.cursor()
        self.cursor.execute(sqlstate) #创建
        self.db.commit()
        self.cursor.close()
 
    def execute(self, sqlstate):
        """
        @todo: 执行Sql语句，如增删改都行
        """
        self.cursor = self.db.cursor()
        self.cursor.execute(sqlstate) 
        self.db.commit()
        self.cursor.close()
 
    def query(self, sqlstate):
        '''
        @todo: 执行查询，返回所有结果
        '''
        self.cursor = self.db.cursor()
        self.cursor.execute(sqlstate) #查
        qres = self.cursor.fetchall()
        self.cursor.close()
        return qres
 
    def one_query(self, sqlstate):
        '''
        @todo: 执行查询，返回第一条结果
        '''
        self.cursor = self.db.cursor()
        self.cursor.execute(sqlstate) #查
        qres = self.cursor.fetchone()
        self.cursor.close()
        return qres
 
    def close_connection(self):
        '''
        @todo: 数据库使用结束后，需要关闭连接
        '''
        self.db.close()
        